﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using DataSystem;
using FairyGUI;
using Newtonsoft.Json;
using TerrainSystem;
using UnityEngine;
using Utility;
using Utility.DataSystem;
using Utility.Math;
using Utility.PoolSystem;
using Utility.Random;


public class Game_Construction
{
	Game Game => Main.Game;
	TerrainObject Terrain => Game.Terrain;

	public Vector2Int? MouseCoord => Game.MouseCoord;
	public Vector2Int? BuildCoord { get; private set; }

	public IBuildable OnBuildObject { get; private set; }

	public bool InConstruction { get; set; }
	public void Start ()
	{
		
	}

	public void End ()
	{

	}

	public void Update ()
	{
	
	}

	#region remove
	public bool TryRemove (bool returnItem = true)
	{
		if (!MouseCoord.HasValue)
		{
			return false;
		}
		var coord = MouseCoord.Value;
		var terrainData = Terrain.Data;

		//remove tilegroup
		{
			var tileGroupRef = terrainData.GetTileGroup (coord);
			var tileGroup = tileGroupRef.Component;
			if (tileGroup)
			{
				//if (Build_IsNewAdded (tileGroup))
				{
					//remove tile group
					if (returnItem)
					{
						//Inventory.Add (tileGroup.Setting);
					}

					terrainData.RemoveTileGroup (tileGroupRef);
					tileGroupRef.Despawn ();

					return true;
				}
//				else
//				{
//					return false;
//				}
			}
		}

		return false;
	}

	#endregion
	#region build
	public void Build_Start (IBuildableSetting context)
	{
		if (context is TileGroupSetting)
		{
			var tileGroup = TileGroup.Spawn (context as TileGroupSetting);
			OnBuildObject = tileGroup.Component;
		}
	}

	public void Build_End ()
	{
		if (OnBuildObject != null)
		{
			OnBuildObject.Despawn ();
			OnBuildObject = null;
		}
	}

	public void Build_Update ()
	{
		BuildCoord = OnBuildObject?.CanViewPlace (Terrain, MouseCoord) ?? false ? MouseCoord : null;
		OnBuildObject?.UpdatePosition (Terrain, BuildCoord);
	}

	public void Build_Rotate ()
	{
		OnBuildObject?.Rotate ();
	}

	public void Build_Flip ()
	{
		OnBuildObject?.Flip ();
	}
	
	public bool Build_TryPlace ()
	{
		if (OnBuildObject?.TryPlace (Terrain, BuildCoord) ?? false)
		{
			Build_Record (OnBuildObject);
			OnBuildObject = null;
			return true;
		}
		return false;
	}

	void Build_Record (IBuildable buildable)
	{
		Terrain.Data.NewAddedBuildable.Add (buildable);
	}

	bool Build_IsNewAdded (IBuildable buildable)
	{
		return Terrain.Data.NewAddedBuildable.Contains (buildable);
	}
	#endregion

}
